using System;
using System.Collections.Generic;
using Volo.Abp.Application.Dtos;
using TenantManagementService.Tenants;

namespace TenantManagementService.Tenants
{
    /// <summary>
    /// 租户DTO
    /// </summary>
    public class TenantDto : FullAuditedEntityDto<Guid>
    {
        /// <summary>
        /// 租户编码
        /// </summary>
        public string Code { get; set; } = string.Empty;

        /// <summary>
        /// 租户名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 租户描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 租户类型
        /// </summary>
        public TenantType Type { get; set; }

        /// <summary>
        /// 租户状态
        /// </summary>
        public TenantStatus Status { get; set; }

        /// <summary>
        /// 租户Logo URL
        /// </summary>
        public string? LogoUrl { get; set; }

        /// <summary>
        /// 租户主题配置
        /// </summary>
        public Dictionary<string, object>? ThemeSettings { get; set; }

        /// <summary>
        /// 数据库连接字符串（脱敏）
        /// </summary>
        public string? ConnectionString { get; set; }

        /// <summary>
        /// 主机地址
        /// </summary>
        public string? Host { get; set; }

        /// <summary>
        /// 租户管理员邮箱
        /// </summary>
        public string? AdminEmail { get; set; }

        /// <summary>
        /// 租户管理员手机号（脱敏）
        /// </summary>
        public string? AdminPhoneNumber { get; set; }

        /// <summary>
        /// 最大用户数
        /// </summary>
        public int MaxUserCount { get; set; }

        /// <summary>
        /// 当前用户数
        /// </summary>
        public int CurrentUserCount { get; set; }

        /// <summary>
        /// 最大存储空间（MB）
        /// </summary>
        public long MaxStorageSize { get; set; }

        /// <summary>
        /// 当前存储使用量（MB）
        /// </summary>
        public long CurrentStorageUsage { get; set; }

        /// <summary>
        /// 试用开始时间
        /// </summary>
        public DateTime? TrialStartTime { get; set; }

        /// <summary>
        /// 试用结束时间
        /// </summary>
        public DateTime? TrialEndTime { get; set; }

        /// <summary>
        /// 订阅开始时间
        /// </summary>
        public DateTime? SubscriptionStartTime { get; set; }

        /// <summary>
        /// 订阅结束时间
        /// </summary>
        public DateTime? SubscriptionEndTime { get; set; }

        /// <summary>
        /// 租户设置
        /// </summary>
        public Dictionary<string, object>? Settings { get; set; }

        /// <summary>
        /// 功能开关
        /// </summary>
        public Dictionary<string, bool>? FeatureSwitches { get; set; }

        /// <summary>
        /// 自定义属性
        /// </summary>
        public Dictionary<string, object>? CustomProperties { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; }

        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime? LastAccessTime { get; set; }

        /// <summary>
        /// 最后激活时间
        /// </summary>
        public DateTime? LastActivationTime { get; set; }

        /// <summary>
        /// 延期次数
        /// </summary>
        public int ExtensionCount { get; set; }

        // 计算属性

        /// <summary>
        /// 是否过期
        /// </summary>
        public bool IsExpired => CalculateIsExpired();

        /// <summary>
        /// 是否试用中
        /// </summary>
        public bool IsTrial => Status == TenantStatus.Trial;

        /// <summary>
        /// 是否即将过期（7天内）
        /// </summary>
        public bool IsExpiringSoon => CalculateIsExpiringSoon();

        /// <summary>
        /// 剩余订阅天数
        /// </summary>
        public int? SubscriptionDaysRemaining => CalculateSubscriptionDaysRemaining();

        /// <summary>
        /// 试用剩余天数
        /// </summary>
        public int? TrialDaysRemaining => CalculateTrialDaysRemaining();

        /// <summary>
        /// 用户使用率（百分比）
        /// </summary>
        public double UserUsagePercentage => CalculateUserUsagePercentage();

        /// <summary>
        /// 存储使用率（百分比）
        /// </summary>
        public double StorageUsagePercentage => CalculateStorageUsagePercentage();

        /// <summary>
        /// 是否用户数超限
        /// </summary>
        public bool IsUserLimitExceeded => CurrentUserCount >= MaxUserCount;

        /// <summary>
        /// 是否存储超限
        /// </summary>
        public bool IsStorageLimitExceeded => CurrentStorageUsage >= MaxStorageSize;

        /// <summary>
        /// 最后访问描述
        /// </summary>
        public string LastAccessDescription => GetLastAccessDescription();

        /// <summary>
        /// 租户类型描述
        /// </summary>
        public string TypeDescription => GetTypeDescription();

        /// <summary>
        /// 租户状态描述
        /// </summary>
        public string StatusDescription => GetStatusDescription();

        /// <summary>
        /// 状态颜色
        /// </summary>
        public string StatusColor => GetStatusColor();

        // 私有方法

        private bool CalculateIsExpired()
        {
            if (Status == TenantStatus.Disabled || Status == TenantStatus.Deleted)
                return true;

            if (Status == TenantStatus.Trial && TrialEndTime.HasValue)
                return TrialEndTime.Value < DateTime.Now;

            if (SubscriptionEndTime.HasValue)
                return SubscriptionEndTime.Value < DateTime.Now;

            return false;
        }

        private bool CalculateIsExpiringSoon()
        {
            if (IsExpired)
                return false;

            DateTime? expiryTime = Status == TenantStatus.Trial ? TrialEndTime : SubscriptionEndTime;
            if (!expiryTime.HasValue)
                return false;

            return expiryTime.Value <= DateTime.Now.AddDays(7);
        }

        private int? CalculateSubscriptionDaysRemaining()
        {
            if (!SubscriptionEndTime.HasValue || Status == TenantStatus.Trial)
                return null;

            return Math.Max(0, (int)(SubscriptionEndTime.Value - DateTime.Now).TotalDays);
        }

        private int? CalculateTrialDaysRemaining()
        {
            if (!TrialEndTime.HasValue || Status != TenantStatus.Trial)
                return null;

            return Math.Max(0, (int)(TrialEndTime.Value - DateTime.Now).TotalDays);
        }

        private double CalculateUserUsagePercentage()
        {
            if (MaxUserCount <= 0)
                return 0;

            return Math.Round((double)CurrentUserCount / MaxUserCount * 100, 2);
        }

        private double CalculateStorageUsagePercentage()
        {
            if (MaxStorageSize <= 0)
                return 0;

            return Math.Round((double)CurrentStorageUsage / MaxStorageSize * 100, 2);
        }

        private string GetLastAccessDescription()
        {
            if (!LastAccessTime.HasValue)
                return "从未访问";

            var timeSpan = DateTime.Now - LastAccessTime.Value;

            if (timeSpan.TotalMinutes < 1)
                return "刚刚访问";

            if (timeSpan.TotalHours < 1)
                return $"{(int)timeSpan.TotalMinutes} 分钟前";

            if (timeSpan.TotalDays < 1)
                return $"{(int)timeSpan.TotalHours} 小时前";

            if (timeSpan.TotalDays < 7)
                return $"{(int)timeSpan.TotalDays} 天前";

            return LastAccessTime.Value.ToString("yyyy-MM-dd HH:mm");
        }

        private string GetTypeDescription()
        {
            return Type switch
            {
                TenantType.Trial => "免费试用",
                TenantType.Basic => "基础版",
                TenantType.Professional => "专业版",
                TenantType.Enterprise => "企业版",
                TenantType.Custom => "定制版",
                TenantType.Internal => "内部租户",
                TenantType.Development => "开发租户",
                TenantType.Testing => "测试租户",
                TenantType.Demo => "演示租户",
                _ => "未知"
            };
        }

        private string GetStatusDescription()
        {
            return Status switch
            {
                TenantStatus.Initializing => "正在初始化",
                TenantStatus.Active => "活跃",
                TenantStatus.Suspended => "已暂停",
                TenantStatus.Disabled => "已禁用",
                TenantStatus.Deleting => "正在删除",
                TenantStatus.Deleted => "已删除",
                TenantStatus.Expired => "已过期",
                TenantStatus.Trial => "试用中",
                TenantStatus.Maintenance => "维护中",
                _ => "未知"
            };
        }

        private string GetStatusColor()
        {
            return Status switch
            {
                TenantStatus.Active => "green",
                TenantStatus.Initializing => "blue",
                TenantStatus.Trial => "orange",
                TenantStatus.Suspended => "yellow",
                TenantStatus.Disabled => "red",
                TenantStatus.Deleted => "gray",
                TenantStatus.Expired => "red",
                TenantStatus.Maintenance => "purple",
                _ => "default"
            };
        }
    }

    /// <summary>
    /// 创建租户DTO
    /// </summary>
    public class CreateTenantDto
    {
        /// <summary>
        /// 租户编码
        /// </summary>
        public string Code { get; set; } = string.Empty;

        /// <summary>
        /// 租户名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 租户描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 租户类型
        /// </summary>
        public TenantType Type { get; set; } = TenantType.Basic;

        /// <summary>
        /// 租户Logo URL
        /// </summary>
        public string? LogoUrl { get; set; }

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string? ConnectionString { get; set; }

        /// <summary>
        /// 主机地址
        /// </summary>
        public string? Host { get; set; }

        /// <summary>
        /// 租户管理员邮箱
        /// </summary>
        public string? AdminEmail { get; set; }

        /// <summary>
        /// 租户管理员手机号
        /// </summary>
        public string? AdminPhoneNumber { get; set; }

        /// <summary>
        /// 最大用户数
        /// </summary>
        public int MaxUserCount { get; set; } = 100;

        /// <summary>
        /// 最大存储空间（MB）
        /// </summary>
        public long MaxStorageSize { get; set; } = 1024;

        /// <summary>
        /// 试用开始时间
        /// </summary>
        public DateTime? TrialStartTime { get; set; }

        /// <summary>
        /// 试用结束时间
        /// </summary>
        public DateTime? TrialEndTime { get; set; }

        /// <summary>
        /// 订阅开始时间
        /// </summary>
        public DateTime? SubscriptionStartTime { get; set; }

        /// <summary>
        /// 订阅结束时间
        /// </summary>
        public DateTime? SubscriptionEndTime { get; set; }

        /// <summary>
        /// 租户设置
        /// </summary>
        public Dictionary<string, object>? Settings { get; set; }

        /// <summary>
        /// 功能开关
        /// </summary>
        public Dictionary<string, bool>? FeatureSwitches { get; set; }

        /// <summary>
        /// 自定义属性
        /// </summary>
        public Dictionary<string, object>? CustomProperties { get; set; }

        /// <summary>
        /// 主题设置
        /// </summary>
        public Dictionary<string, object>? ThemeSettings { get; set; }

        /// <summary>
        /// 是否立即激活
        /// </summary>
        public bool AutoActivate { get; set; } = true;

        /// <summary>
        /// 是否发送欢迎邮件
        /// </summary>
        public bool SendWelcomeEmail { get; set; } = true;
    }

    /// <summary>
    /// 更新租户DTO
    /// </summary>
    public class UpdateTenantDto
    {
        /// <summary>
        /// 租户名称
        /// </summary>
        public string? Name { get; set; }

        /// <summary>
        /// 租户描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 租户Logo URL
        /// </summary>
        public string? LogoUrl { get; set; }

        /// <summary>
        /// 主题设置
        /// </summary>
        public Dictionary<string, object>? ThemeSettings { get; set; }

        /// <summary>
        /// 租户管理员邮箱
        /// </summary>
        public string? AdminEmail { get; set; }

        /// <summary>
        /// 租户管理员手机号
        /// </summary>
        public string? AdminPhoneNumber { get; set; }

        /// <summary>
        /// 租户设置
        /// </summary>
        public Dictionary<string, object>? Settings { get; set; }

        /// <summary>
        /// 功能开关
        /// </summary>
        public Dictionary<string, bool>? FeatureSwitches { get; set; }

        /// <summary>
        /// 自定义属性
        /// </summary>
        public Dictionary<string, object>? CustomProperties { get; set; }

        /// <summary>
        /// 最大用户数
        /// </summary>
        public int? MaxUserCount { get; set; }

        /// <summary>
        /// 最大存储空间（MB）
        /// </summary>
        public long? MaxStorageSize { get; set; }
    }

    /// <summary>
    /// 租户统计信息DTO
    /// </summary>
    public class TenantStatisticsDto
    {
        /// <summary>
        /// 总租户数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 活跃租户数
        /// </summary>
        public int ActiveCount { get; set; }

        /// <summary>
        /// 暂停租户数
        /// </summary>
        public int SuspendedCount { get; set; }

        /// <summary>
        /// 禁用租户数
        /// </summary>
        public int DisabledCount { get; set; }

        /// <summary>
        /// 试用租户数
        /// </summary>
        public int TrialCount { get; set; }

        /// <summary>
        /// 过期租户数
        /// </summary>
        public int ExpiredCount { get; set; }

        /// <summary>
        /// 按类型分组的租户数
        /// </summary>
        public Dictionary<TenantType, int> TypeDistribution { get; set; } = new();

        /// <summary>
        /// 按状态分组的租户数
        /// </summary>
        public Dictionary<TenantStatus, int> StatusDistribution { get; set; } = new();

        /// <summary>
        /// 本月新增租户数
        /// </summary>
        public int NewThisMonth { get; set; }

        /// <summary>
        /// 本月激活租户数
        /// </summary>
        public int ActivatedThisMonth { get; set; }

        /// <summary>
        /// 总用户数
        /// </summary>
        public int TotalUsers { get; set; }

        /// <summary>
        /// 总存储使用量（MB）
        /// </summary>
        public long TotalStorageUsage { get; set; }

        /// <summary>
        /// 平均用户数
        /// </summary>
        public double AverageUserCount { get; set; }

        /// <summary>
        /// 平均存储使用量（MB）
        /// </summary>
        public double AverageStorageUsage { get; set; }

        /// <summary>
        /// 租户活跃率（百分比）
        /// </summary>
        public double ActiveRate { get; set; }

        /// <summary>
        /// 试用转化率（百分比）
        /// </summary>
        public double TrialConversionRate { get; set; }
    }

    /// <summary>
    /// 租户使用率统计DTO
    /// </summary>
    public class TenantUsageStatisticsDto
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public Guid TenantId { get; set; }

        /// <summary>
        /// 租户名称
        /// </summary>
        public string TenantName { get; set; } = string.Empty;

        /// <summary>
        /// 租户编码
        /// </summary>
        public string TenantCode { get; set; } = string.Empty;

        /// <summary>
        /// 当前用户数
        /// </summary>
        public int CurrentUserCount { get; set; }

        /// <summary>
        /// 最大用户数
        /// </summary>
        public int MaxUserCount { get; set; }

        /// <summary>
        /// 用户使用率（百分比）
        /// </summary>
        public double UserUsagePercentage { get; set; }

        /// <summary>
        /// 当前存储使用量（MB）
        /// </summary>
        public long CurrentStorageUsage { get; set; }

        /// <summary>
        /// 最大存储空间（MB）
        /// </summary>
        public long MaxStorageSize { get; set; }

        /// <summary>
        /// 存储使用率（百分比）
        /// </summary>
        public double StorageUsagePercentage { get; set; }

        /// <summary>
        /// 是否用户数超限
        /// </summary>
        public bool IsUserLimitExceeded { get; set; }

        /// <summary>
        /// 是否存储超限
        /// </summary>
        public bool IsStorageLimitExceeded { get; set; }

        /// <summary>
        /// 订阅剩余天数
        /// </summary>
        public int? SubscriptionDaysRemaining { get; set; }

        /// <summary>
        /// 试用剩余天数
        /// </summary>
        public int? TrialDaysRemaining { get; set; }

        /// <summary>
        /// 是否即将过期
        /// </summary>
        public bool IsExpiringSoon { get; set; }

        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime? LastAccessTime { get; set; }

        /// <summary>
        /// 最后访问描述
        /// </summary>
        public string LastAccessDescription { get; set; } = string.Empty;

        /// <summary>
        /// 本月新增用户数
        /// </summary>
        public int NewUsersThisMonth { get; set; }

        /// <summary>
        /// 本月存储增长（MB）
        /// </summary>
        public long StorageGrowthThisMonth { get; set; }

        /// <summary>
        /// API调用次数
        /// </summary>
        public long ApiCallCount { get; set; }

        /// <summary>
        /// 带宽使用量（MB）
        /// </summary>
        public long BandwidthUsage { get; set; }

        /// <summary>
        /// 健康检查得分
        /// </summary>
        public double HealthScore { get; set; }

        /// <summary>
        /// 风险等级
        /// </summary>
        public RiskLevel RiskLevel { get; set; }
    }

    /// <summary>
    /// 批量操作结果DTO
    /// </summary>
    public class BatchOperationResultDto
    {
        /// <summary>
        /// 总操作数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 成功数
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 失败数
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 跳过数
        /// </summary>
        public int SkippedCount { get; set; }

        /// <summary>
        /// 成功的租户ID列表
        /// </summary>
        public List<Guid> SuccessIds { get; set; } = new();

        /// <summary>
        /// 失败的租户ID列表
        /// </summary>
        public List<Guid> FailureIds { get; set; } = new();

        /// <summary>
        /// 跳过的租户ID列表
        /// </summary>
        public List<Guid> SkippedIds { get; set; } = new();

        /// <summary>
        /// 错误信息
        /// </summary>
        public List<string> Errors { get; set; } = new();

        /// <summary>
        /// 失败记录详细信息
        /// </summary>
        public List<ImportFailureRecord> Failures { get; set; } = new();

        /// <summary>
        /// 操作开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 操作结束时间
        /// </summary>
        public DateTime EndTime { get; set; }

        /// <summary>
        /// 操作耗时（毫秒）
        /// </summary>
        public long DurationMs { get; set; }
    }

    /// <summary>
    /// 导入结果DTO
    /// </summary>
    public class ImportResultDto
    {
        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalRecords { get; set; }

        /// <summary>
        /// 成功导入数
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 更新数
        /// </summary>
        public int UpdatedCount { get; set; }

        /// <summary>
        /// 失败数
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 跳过的租户ID列表
        /// </summary>
        public List<Guid> SkippedIds { get; set; } = new();

        /// <summary>
        /// 成功的租户列表
        /// </summary>
        public List<TenantDto> SuccessTenants { get; set; } = new();

        /// <summary>
        /// 失败的记录
        /// </summary>
        public List<ImportFailureRecord> Failures { get; set; } = new();

        /// <summary>
        /// 导入开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 导入结束时间
        /// </summary>
        public DateTime EndTime { get; set; }

        /// <summary>
        /// 导入耗时（毫秒）
        /// </summary>
        public long DurationMs { get; set; }
    }

    /// <summary>
    /// 导入失败记录
    /// </summary>
    public class ImportFailureRecord
    {
        /// <summary>
        /// 行号
        /// </summary>
        public int RowNumber { get; set; }

        /// <summary>
        /// 原始数据
        /// </summary>
        public Dictionary<string, object>? RawData { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;

        /// <summary>
        /// 错误类型
        /// </summary>
        public string ErrorType { get; set; } = string.Empty;

        /// <summary>
        /// 修复建议
        /// </summary>
        public string? Suggestion { get; set; }
    }

    /// <summary>
    /// 验证结果DTO
    /// </summary>
    public class ValidationResultDto
    {
        /// <summary>
        /// 是否有效
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 总体得分
        /// </summary>
        public double OverallScore { get; set; }

        /// <summary>
        /// 验证项列表
        /// </summary>
        public List<ValidationItemDto> ValidationItems { get; set; } = new();

        /// <summary>
        /// 验证时间
        /// </summary>
        public DateTime ValidationTime { get; set; }

        /// <summary>
        /// 风险等级
        /// </summary>
        public RiskLevel RiskLevel { get; set; }

        /// <summary>
        /// 建议
        /// </summary>
        public List<string> Recommendations { get; set; } = new();
    }

    /// <summary>
    /// 验证项DTO
    /// </summary>
    public class ValidationItemDto
    {
        /// <summary>
        /// 验证项名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 验证项描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 是否通过
        /// </summary>
        public bool IsPassed { get; set; }

        /// <summary>
        /// 得分
        /// </summary>
        public double Score { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 详细信息
        /// </summary>
        public Dictionary<string, object>? Details { get; set; }
    }

    /// <summary>
    /// 租户配置DTO
    /// </summary>
    public class TenantConfigurationsDto
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public Guid TenantId { get; set; }

        /// <summary>
        /// 租户名称
        /// </summary>
        public string TenantName { get; set; } = string.Empty;

        /// <summary>
        /// 配置列表
        /// </summary>
        public List<TenantConfigurationDto> Configurations { get; set; } = new();

        /// <summary>
        /// 按组分组的配置
        /// </summary>
        public Dictionary<string, List<TenantConfigurationDto>> GroupedConfigurations { get; set; } = new();
    }

    /// <summary>
    /// 租户配置项DTO
    /// </summary>
    public class TenantConfigurationDto
    {
        /// <summary>
        /// 配置ID
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// 配置键
        /// </summary>
        public string Key { get; set; } = string.Empty;

        /// <summary>
        /// 配置值
        /// </summary>
        public string Value { get; set; } = string.Empty;

        /// <summary>
        /// 配置组
        /// </summary>
        public string? Group { get; set; }

        /// <summary>
        /// 配置描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 是否加密存储
        /// </summary>
        public bool IsEncrypted { get; set; }

        /// <summary>
        /// 是否只读
        /// </summary>
        public bool IsReadOnly { get; set; }

        /// <summary>
        /// 配置类型
        /// </summary>
        public ConfigurationType Type { get; set; }

        /// <summary>
        /// 默认值
        /// </summary>
        public string? DefaultValue { get; set; }

        /// <summary>
        /// 验证规则
        /// </summary>
        public string? ValidationRules { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreationTime { get; set; }

        /// <summary>
        /// 最后修改时间
        /// </summary>
        public DateTime? LastModificationTime { get; set; }
    }

    /// <summary>
    /// 风险等级
    /// </summary>
    public enum RiskLevel
    {
        /// <summary>
        /// 低风险
        /// </summary>
        Low = 1,

        /// <summary>
        /// 中等风险
        /// </summary>
        Medium = 2,

        /// <summary>
        /// 高风险
        /// </summary>
        High = 3,

        /// <summary>
        /// 极高风险
        /// </summary>
        Critical = 4
    }

    }